//
//  AppDelegate.m
//  MPTLive
//
//  Created by Jeakin on 8/12/15.
//  Copyright © 2015 Jeakin. All rights reserved.
//

#import "AppDelegate.h"
#import <JLRoutes.h>
#import <MPTRoute.h>
#import <MPTLoginApp.h>
#import <MPTLoginAdapter.h>
// 融云sdk
#import <RongIMLib/RongIMLib.h>
#import "MobClick.h"
#import "MPTLiveHomeVC.h"
#import "MPTLiveMeVC.h"
#import "MPTLiveViewController.h"
#import "MPTLiveLoginVC.h"
#import "MPTLoginApp.h"
#import "NSString+MPTString.h"
#import <AudioToolbox/AudioToolbox.h>
#import "MPTLiveHomeCenterVC.h"
#import <UIWindow+MPTWindow.h>
#import "MPTLivePushView.h"
#import <MPTLivePlayerVC.h>
#import "MPTLiveIMManager.h"
#import "UIViewController+MLTransition.h"
#import <UIImageView+WebCache.h>


static BOOL isFromBackToFront = NO;

@interface AppDelegate ()
<
TPTabBarManagerDelegate,
MPTRoutingDelegate
>
{
    TPTabBarManager *manager;
    
    NSTimeInterval  fltshijian;
}

@property (nonatomic, strong) NSDictionary *pushDict;

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [AMapLocationServices sharedServices].apiKey = @"6a9514887d12e34fa065f9fb6224ca80";
    [AMapSearchServices sharedServices].apiKey = @"6a9514887d12e34fa065f9fb6224ca80";
    
    [MobClick setCrashReportEnabled:NO];
    [MobClick startWithAppkey:@"561cbe62e0f55ac81c004d79" reportPolicy:SEND_ON_EXIT channelId:@""];
    
    /// 使用Version号进行数据收集
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [MobClick setAppVersion:ZB_Str_Protect(version)];
    
    [[MPTLoginApp routesToRegister] enumerateObjectsUsingBlock:^(MPTRoute *route, NSUInteger idx, BOOL *stop) {
        [JLRoutes addRoute:route.url handler:^BOOL(NSDictionary *parameters) {
            route.action(self, route.url, parameters);
            return YES;
        }];
    }];
        
    
    //初始化融云SDK，
    [[RCIMClient sharedRCIMClient] init:@"qd46yzrf4o2ff"];
    
    /// 推送授权
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    {
        [[UIApplication sharedApplication] registerUserNotificationSettings:
         [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge)
                                           categories:nil]];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    } else
    {
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
         (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];
    }
    
    ///清除推送角标
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;

    /// 初始化试图的逻辑
    [self AppFoution];
    
    // 通过推送唤起
    if (launchOptions)
    {
        self.pushDict = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        [self performSelector:@selector(handlePushNotify) withObject:nil afterDelay:0.5];
    }
    
    /// 添加弹出pushVC消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushModelVC) name:@"pushModelVC" object:nil];
    
    [UIViewController validatePanPackWithMLTransitionGestureRecognizerType:MLTransitionGestureRecognizerTypeScreenEdgePan];
    
    // Override point for customization after application launch.
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"appGoBg" object:nil]; // 后台
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    fltshijian =[dat timeIntervalSince1970];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    isFromBackToFront = YES;
//    // 后台到前台
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970] ;
    NSLog(@"前台%f", a);
    
    /// 在后台超过3分钟后回到前台直接直播结束
    if (a - fltshijian >= 180)
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"appGoBg" object:nil];
 
    }
    else
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"startTuiLiu" object:nil];
 
    }
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    isFromBackToFront = NO;
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark - 通知相关
 - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    [[UIApplication sharedApplication] registerForRemoteNotifications];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    
    
}

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    NSString *deviceTokenString = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    deviceTokenString = [deviceTokenString stringByReplacingOccurrencesOfString:@" " withString:@""];
        NSLog(@"%@",deviceTokenString);
    
    if (![[[NSUserDefaults standardUserDefaults] objectForKey:@"devicekToken"] isEqualToString:deviceTokenString])
    {
        /// 上传token
        [self updateToken:deviceTokenString];
    }

}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    ///  震动
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    /// 声音
    AudioServicesPlaySystemSound(1007);
    self.pushDict = userInfo;
    
    if (!isFromBackToFront)
    {
        if (self.pushDict)
        {
            MPTLivePushView *viewpush = [[MPTLivePushView alloc] initWithFrame:CGRectMake(0, -64, screenW, 64) dic:self.pushDict];
            [viewpush setBlock:^()
             {
                 [self handlePushNotify];
             }];
            [[UIApplication sharedApplication] setStatusBarHidden:YES];
            [self.window addSubview:viewpush];
            
            [UIView animateWithDuration:0.3 animations:^{
                viewpush.frame = CGRectMake(0, 0, screenW, 64);
            }];
        }
    }
    else
    {
        /// 处理推送逻辑
        [self handlePushNotify];
    }

}

/// 处理推送唤起逻辑
- (void)handlePushNotify
{
    [manager jumpToNav:BottomIndex_A];
    
    [self clearAllVC];
    
    if (_pushDict[@"action"])
    {
        NSString *str = _pushDict[@"action"];
        NSArray *ary = [str componentsSeparatedByString:@","];
        if (ary.count == 2)
        {
            if ([[ary firstObject] isKindOfClass:[NSString class]])
            {
                if ([[ary firstObject] isEqualToString:@"live"])
                {
                    if ([[ary lastObject] isKindOfClass:[NSString class]])
                    {
                        /// 记录播放状态
                        if (![MPTLiveIMManager sharedInstance].isPlaying)
                        {
                            [self pushModelVC];
                        }
                        else
                        {
                            /// 发送释放VC的消息
                            [[NSNotificationCenter defaultCenter] postNotificationName:@"closeModelVC" object:nil];
                        }
                    }
                }
            }
        }
    }
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    // 删除消息中心的推送消息，不过这个方法不是很好使，但是网上也没有好的方法，暂时先用上吧，以后有方法在替换
    [[UIApplication sharedApplication] cancelAllLocalNotifications];

}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    if ([[url scheme] isEqualToString:@"miaopailive"])
    {
        return YES;
    }
    else
    {
        return [[[MPTLoginAdapter alloc] init] routeURL:url sourceApplication:sourceApplication];
    }
}

- (void)shouldPushViewController:(UIViewController *)controller
{
    [((UINavigationController *) self.window.rootViewController) pushViewController:controller animated:YES];
}

- (void)shouldpresentViewController:(UIViewController *)controller
{
    [self.window.rootViewController presentViewController:controller animated:YES completion:nil];
}


- (void)shouldaddChildViewController:(UIViewController *)controller
{
    [controller willMoveToParentViewController:self.window.rootViewController];
    [controller.view setFrame:self.window.rootViewController.view.frame];
    [self.window.rootViewController.view addSubview:controller.view];
    [self.window.rootViewController addChildViewController:controller];
    [controller didMoveToParentViewController:self.window.rootViewController];
}

//弹出window的模式
- (void)shouldKeyWindowViewController:(UIViewController *)controller {
    
}

- (void)dismissKeyWindowViewController:(UIViewController *)viewController {
    
}

- (void)selectIndex:(BottomIndex)index lastIndex:(BottomIndex)lastIndex
{
    
}

- (void)AppFoution
{
    if (![MPTLoginApp isLogin])
    {
        MPTLiveLoginVC *vcLogin = [[MPTLiveLoginVC alloc] init];
        TPNavigationController *nav = [[TPNavigationController alloc] initWithRootViewController:vcLogin];
        
        [vcLogin setBlock:^()
         {
             /// 礼物列表
             [self req_Goods_list];
             [self updateToken:[[NSUserDefaults standardUserDefaults] objectForKey:@"devicekToken"]];
             [self initMainVC];
         }];
        self.window.rootViewController = nav;
    }
    else
    {
        /// 礼物列表
        [self req_Goods_list];
        
        /// 请求用户权限
        [self req_Authory];
        
        [self initMainVC];
    }
}

- (void)initMainVC
{
    /// 首页
    MPTLiveHomeCenterVC *vcHome = [[MPTLiveHomeCenterVC alloc] init];
    TPNavigationController *navHome = [[TPNavigationController alloc] initWithRootViewController:vcHome];
    
    /// 我的
    MPTLiveMeVC *vcMe= [[MPTLiveMeVC alloc] init];
    TPNavigationController *navMe = [[TPNavigationController alloc] initWithRootViewController:vcMe];
    
    manager = [TPTabBarManager share];
    manager.delegate = self;
    [manager setVCArray:@[navHome, navMe]];
    
    NSArray *arySelectAry = @[@"HomeS",@"zhiboS",@"GeRenS"];
    NSArray *aryUnSelectAry = @[@"HomeN",@"zhiboN",@"GeRenN"];
    
    [manager setToorBarTitleAry:nil UnSelectImageAry:aryUnSelectAry selectImageAry:arySelectAry];
    
    self.window = manager.delegateWindow;
}

/// 上报token
- (void)updateToken:(NSString *)strToken
{
    NSDictionary *dic = @{@"id":ZB_Str_Protect(strToken),@"device_type" :@"live"};
    [[MPTHttpClient sharedMPHTTPClient] postPath:@"m/rpt_ios_devid.json" parameters:dic queuePriority:NSOperationQueuePriorityHigh cacheRequest:NO
           success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        if ([responseObject isKindOfClass:[NSDictionary class]])
        {
            if ([responseObject[@"status"] integerValue] == 200)
            {
                [[NSUserDefaults standardUserDefaults] setValue:strToken forKey:@"devicekToken"];
            }
        }
           } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
               
           } cached:nil];
}

/// 白名单接口
- (void)req_Authory
{
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSDictionary *paraDic = @{@"version":ZB_Str_Protect(version),
                              @"unique_id":ZB_Str_Protect([NSString MPTIdentifierString])
                              };
    
    [[MPTHttpClient sharedMPHTTPClient] getPath:@"m/checkLiveAuth.json" parameters:paraDic queuePriority:NSOperationQueuePriorityNormal cacheRequest:NO success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         if ([responseObject isKindOfClass:[NSDictionary class]])
         {
             if ([responseObject[@"status"] integerValue] == 200)
             {
                 /// 保存直播状态
                 [[NSUserDefaults standardUserDefaults] setValue:responseObject[@"code"] forKey:LiveCode];
             }
         }
     }
                                        failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         
     }
                                         cached:^(NSDictionary *cachedObject)
     {
         
     }];
}

#pragma mark - 获取用户礼物列表
- (void)req_Goods_list
{
    NSDictionary *dic = @{@"page":@"1", @"count":@"10"};
    http://api.miaopai.com/
    [[[MPTHttpClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://i.miaopai.com/"]] getPath:@"2/gift/gift_list" parameters:dic queuePriority:NSOperationQueuePriorityNormal cacheRequest:NO success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         /// 加保护获取礼物列表缓存到本地
         if ([responseObject isKindOfClass:[NSDictionary class]])
         {
             if ([responseObject[@"result"] isKindOfClass:[NSDictionary class]])
             {
                 if ([responseObject[@"result"][@"list"] isKindOfClass:[NSArray class]])
                 {
                     NSArray *aryGoodList = [NSArray arrayWithArray:responseObject[@"result"][@"list"]];
                     [[NSUserDefaults standardUserDefaults] setValue:aryGoodList forKey:GoodList];
                     
                     /// 循环缓存图片
                     for (NSInteger i = 0; i < aryGoodList.count; i++)
                     {
                         UIImageView *imagev = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
                         [imagev sd_setImageWithURL:[NSURL URLWithString:aryGoodList[i][@"img"]] placeholderImage:nil];
                     }
                 }
             }
         }
     }
                                        failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         
     } cached:nil];
}

- (void)clearAllVC
{
    TPNavigationController *nav = [manager getNavControllerByIndex:BottomIndex_A];
    
    /// 删除model
    for (UIViewController *vc in nav.viewControllers)
    {
        [self clearVCModel:vc];
    }
    
    /// pop所有
    [nav popToRootViewControllerAnimated:NO];
    
}

- (void )clearVCModel:(UIViewController *)vc
{
    if (vc.parentViewController)
    {
        [vc dismissViewControllerAnimated:NO completion:nil];
    }
    else
    {
        
    }
}

- (void)pushModelVC
{
    if (_pushDict[@"action"])
    {
        NSString *str = _pushDict[@"action"];
        NSArray *ary = [str componentsSeparatedByString:@","];
        if (ary.count == 2)
        {
            if ([[ary firstObject] isKindOfClass:[NSString class]])
            {
                if ([[ary firstObject] isEqualToString:@"live"])
                {
                    if ([[ary lastObject] isKindOfClass:[NSString class]])
                    {
                        /// 发送释放VC的消息
                        MPTLivePlayerVC *vc = [[MPTLivePlayerVC alloc] initWithScid:[ary lastObject]];
                        [[UIApplication sharedApplication].keyWindow.visibleViewController presentViewController:vc animated:YES completion:nil];
                    }
                }
            }
        }
    }

}

@end
